package com.sanpu.kxe.business.main.presenter;

import com.sanpu.kxe.business.main.bean.PartnerInfoOutput;
import com.sanpu.kxe.business.main.bean.UserCenterOutput;
import com.sanpu.kxe.business.main.contract.PartnerContract;
import com.sanpu.kxe.business.main.model.MainModel;
import com.sanpu.kxe.common.cache.CacheManage;
import com.sanpu.kxe.common.cache.CacheModel;

import rx.Observer;
import rx.Subscription;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

/**
 * Description：合伙人
 * Created by 薛勇军 on 2018/7/13.
 */

public class PartnerPresenter implements PartnerContract.Presenter {

    private PartnerContract.View mView;

    private CompositeSubscription mSubscription;

    public PartnerPresenter(PartnerContract.View mView) {
        this.mView = mView;
        mSubscription = new CompositeSubscription();
    }

    @Override
    public void showViewData() {
        UserCenterOutput output = CacheManage.getInstance().getCache(CacheModel.USER_CENTER_KEY);
        if (output != null && output.isPartner()) {
            Subscription subscription = MainModel.getInstance().partnerInf()
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<PartnerInfoOutput>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                            mView.showErrorText(e);
                        }

                        @Override
                        public void onNext(PartnerInfoOutput infoOutput) {
                            if (infoOutput != null) {
                                mView.showPartnerLvl(infoOutput.getPartnerLvl());
                                int allNum = infoOutput.getRefNum()+infoOutput.getUndRefNum();
                                mView.showPartnerData(allNum, infoOutput.getUndRefNum(),
                                        infoOutput.getUndDayReb(), infoOutput.getUndAccReb());
                                mView.showReservedView(infoOutput.isReserved(),
                                        infoOutput.getUncashAmount());
                            }
                        }
                    });
            mSubscription.add(subscription);
        }
        mView.showPartnerView(output != null && output.isPartner());
    }

    @Override
    public void onDestroyPresenter() {
        if (mView != null) {
            mView = null;
        }
        if (mSubscription != null && !mSubscription.isUnsubscribed()) {
            mSubscription.unsubscribe();
            mSubscription = null;
        }
    }
}
